package com.gxuwz.stats.controller.twoAdmin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.AchievementTransfer;
import com.gxuwz.stats.entity.NatureResearchAward;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.NatureResearchAwardService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/twoNatureReAward")
public class NatureResearchAwardTwoController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private NatureResearchAwardService natureResearchAwardService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getTwoNatureReAwardList")
    public ResponseEntity<Map<String, Object>> getNatureReAwardList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            // 提取 Token 并解析用户信息
            String token = authorization.replace("Bearer ", "");
//            int userId = jwtTokenUtil.getUserIdFromToken(token);
            String department = jwtTokenUtil.getDepartmentFromToken(token); // 获取部门信息

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<NatureResearchAward> page = new Page<>(currentPage, pageSize);
//            QueryWrapper<AchievementTransfer> queryWrapper = new QueryWrapper<>();


            // 调用 service 层的分页查询方法
            IPage<NatureResearchAward> resultPage = natureResearchAwardService.getToAdminnaturaReList(page, department,
                    params.get("username"),
                    params.get("naturaReName"),
                    params.get("naturaReCategory"));

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addTwoAdminNatureReAward")
    public ResponseEntity<Map<String, Object>> saveNatureReAward(@RequestBody NatureResearchAward natureResearchAward) {
        System.out.println("前端数据：" + natureResearchAward);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = natureResearchAward.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
//        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        natureResearchAward.setUserId(userId);
        // 1. 自动计算分值
        int baseScore = natureResearchAwardService.getScoreByType(natureResearchAward.getNatureCategory());
        natureResearchAward.setNatureScore(baseScore);

        // 2. 计算总分值
        natureResearchAwardService.calculateTotalScore(natureResearchAward);

        try {
            // 保存到数据库
            natureResearchAwardService.save(natureResearchAward);

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改
     */
    @PutMapping("/updateTwoAdminNatureReAward")
    public ResponseEntity<Map<String, Object>> updateNatureReAward(
            @RequestBody NatureResearchAward natureResearchAward
    ) {
        // 1. 获取前端传递的用户名
        String username = natureResearchAward.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            natureResearchAward.setUserId(user.getUserId());
        }
        // 1. 自动计算分值
        int baseScore = natureResearchAwardService.getScoreByType(natureResearchAward.getNatureCategory());
        natureResearchAward.setNatureScore(baseScore);

        // 2. 计算总分值
        natureResearchAwardService.calculateTotalScore(natureResearchAward);

        natureResearchAwardService.updateById(natureResearchAward);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delTwoAdminNatureReAward")
    public ResponseEntity<Map<String, Object>> deleteToAdminNatureReAward(@RequestBody List<Long> natureResearchAwardIds) {
        natureResearchAwardService.removeByIds(natureResearchAwardIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

}
